package com.gid.rcflightlogger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.orm.androrm.Filter;

public class FlightLogBrowseActivity extends BaseActivity {

	
	//db objects
	private List<Flight> mFlights;
	private List<Aircraft> mAircrafts;
	private Aircraft mEmptyAircraft;
	
	private ArrayAdapter<Aircraft> mAircraftSpinnerAdapter;
	private ArrayAdapter<String> mTimeFilterSpinnerAdapter; 
	//others
	private final String[] mTimeFilterLabels = {"",	"Last month",			"Last 3 months",			"Last 6 months",			"Last year", 				"Last 2 years", 			"Last 3 years"};
	private final long[] mTimeFilterOffsets = {0,	(long)30*24*60*60*1000,	(long)3*30*24*60*60*1000,	(long)6*30*24*60*60*1000,	(long)12*30*24*60*60*1000,	(long)24*30*24*60*60*1000, 	(long)36*30*24*60*60*1000}; //in milliseconds
	
	//layout objects
	private TableLayout mTableLayout;
	private Spinner mAircraftSpinner;
	private Spinner mTimeFilterSpinner;
	
	private int mSelectedId = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_flightlogbrowse);
        mCurrentMenuID = R.id.menu_main_logs_flights;
       
        mFlights = new ArrayList<Flight>();
        mAircrafts = new ArrayList<Aircraft>();
        mEmptyAircraft = new Aircraft();
        mAircraftSpinnerAdapter = new ArrayAdapter<Aircraft>(this, android.R.layout.simple_spinner_item, mAircrafts);
        mTimeFilterSpinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mTimeFilterLabels);
        
        //private Spinner mAircraftSpinner;
        mTableLayout = (TableLayout) findViewById(R.id.flightlogbrowse_table);
        mAircraftSpinner = (Spinner) findViewById(R.id.flightlogbrowse_spinner_aircraft);
        mAircraftSpinner.setAdapter(mAircraftSpinnerAdapter);
        mAircraftSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				filterAndDisplayData();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				filterAndDisplayData();
			}
		});
        mTimeFilterSpinner = (Spinner) findViewById(R.id.flightlogbrowse_spinner_time);
        mTimeFilterSpinner.setAdapter(mTimeFilterSpinnerAdapter);
        mTimeFilterSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				filterAndDisplayData();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				filterAndDisplayData();
			}
		});
	}
	
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
        filterAndDisplayData();
    }
	
	private void loadData() {
		//reload data from database
		mFlights.clear();
		Filter ffilter = new Filter();
		ffilter.is("mFake", 0);
		mFlights.addAll(Flight.objects(getApplicationContext()).filter(ffilter).orderBy("-mDate").toList());
		
		mAircrafts.clear();
		Filter afilter = new Filter();
		mAircrafts.add(mEmptyAircraft);
		mAircrafts.addAll(Aircraft.objects(getApplicationContext()).all().toList());
		mAircraftSpinnerAdapter.notifyDataSetChanged();
	}
	
	private void filterAndDisplayData() {
		int matchId = 0;
		if (mAircraftSpinner.getSelectedItemPosition() > 0)
		{
			matchId = ((Aircraft)(mAircraftSpinner.getSelectedItem())).getId();
		}
		
		Date matchFromDate = null;
		if (mTimeFilterSpinner.getSelectedItemPosition() > 0)
		{
			matchFromDate = new Date();
			long ms = matchFromDate.getTime();
			ms = ms - mTimeFilterOffsets[mTimeFilterSpinner.getSelectedItemPosition()];
			matchFromDate.setTime(ms);
			//myUtils.makeToast(this, "Pos = " + mTimeFilterSpinner.getSelectedItemPosition() + " Offset = " + mTimeFilterOffsets[mTimeFilterSpinner.getSelectedItemPosition()] + " Time = " + myUtils.Date2Str(matchFromDate));
		}
		
		//repopulate table
		mTableLayout.removeViews(2, mTableLayout.getChildCount() - 2); //keep the header and border
		int totalFlights = 0;
		int totalDuration = 0;
		int totalCrashes = 0;
		
		for (Flight flight : mFlights) 
		{
			//skip if filtering criteria not matched
			if ( ((matchId != 0) && (flight.getAircraft(this).getId() != matchId)) || ((matchFromDate != null) && (flight.getDate().before(matchFromDate))))
				continue;
			
			TableRow tr;
			TextView tv;

			totalFlights += flight.getCount();
			totalDuration += flight.getDuration();
			totalCrashes += (flight.getOutcome() != 0) ? 1 : 0;
			
			tr = (TableRow) getLayoutInflater().inflate(R.layout.layout_flightlogbrowse_row, null);
			// Fill out cells
			tv = (TextView) tr.findViewById(R.id.flightlogbrowse_col_date);
			tv.setGravity(Gravity.LEFT);
			tv.setText(myUtils.DateTime2Str(flight.getDate()));
			
			tv = (TextView) tr.findViewById(R.id.flightlogbrowse_col_aircraft);
			tv.setGravity(Gravity.RIGHT);
			tv.setText(flight.getAircraft(this).getName());
			
			tv = (TextView) tr.findViewById(R.id.flightlogbrowse_col_duration);
			tv.setGravity(Gravity.RIGHT);
			tv.setText(myUtils.Duration2Str(flight.getDuration(), false));
   	    
			tv = (TextView) tr.findViewById(R.id.flightlogbrowse_col_crash);
			tv.setGravity(Gravity.RIGHT);
			tv.setText(Flight.FLIGHT_OUTCOME_SYMBOLS[flight.getOutcome()]);
			
			tr.setPadding(0, 2, 0, 0);	
			tr.setId(flight.getId());
			tr.setClickable(true); 
			tr.setOnTouchListener(mRowOnTouchListener);
			tr.setOnLongClickListener(mRowOnLongClickListener);
			tr.setFocusable(true);
			tr.setOnFocusChangeListener(mRowOnFocusChangeListener);
			
			mTableLayout.addView(tr);
			
			//table's horizontal line
			View ruler = new View(getApplicationContext());
			ruler.setBackgroundColor(0x88909090);
			mTableLayout.addView(ruler,new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, 1));
		}
		
		if (totalFlights >= 2) //add a summary
		{
			TableRow tr;
			TextView tv;
			
			tr = (TableRow) getLayoutInflater().inflate(R.layout.layout_flightlogbrowse_row, null);
			// Fill out cells
			tv = (TextView) tr.findViewById(R.id.flightlogbrowse_col_date);
			tv.setGravity(Gravity.LEFT);
			tv.setText("TOTAL");
					
			tv = (TextView) tr.findViewById(R.id.flightlogbrowse_col_duration);
			tv.setGravity(Gravity.RIGHT);
			tv.setText(myUtils.Duration2Str(totalDuration, false));
   	    
			tv = (TextView) tr.findViewById(R.id.flightlogbrowse_col_crash);
			tv.setGravity(Gravity.RIGHT);
			tv.setText(totalCrashes + "/" + totalFlights);
			
			tr.setPadding(0, 2, 0, 0);	
			
			mTableLayout.addView(tr);
			
			//table's horizontal line
			View ruler = new View(getApplicationContext());
			ruler.setBackgroundColor(0x88909090);
			mTableLayout.addView(ruler,new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, 1));
		}
		
	}
	//changes highlighted state of a given table row, by adding or removing bg color
	private void highlightTableRow(TableRow r, boolean highlighted)
	{
		if (highlighted)
		{
			r.setBackgroundColor(Color.rgb(247, 125, 0)); //android default list selector bg color
			r.invalidate();
		}
		else
		{
			r.setBackgroundResource(0);
			r.invalidate();
		}
	}
	
	// ====================================================
	// Various isteners
	// ====================================================
	private TableRow.OnTouchListener mRowOnTouchListener = new TableRow.OnTouchListener()
    {
		@Override
		public boolean onTouch(View v, MotionEvent event)
		{
			final int action = event.getAction();
			switch (action & MotionEvent.ACTION_MASK)
			{
				case MotionEvent.ACTION_UP:
				case MotionEvent.ACTION_CANCEL:
				case MotionEvent.ACTION_OUTSIDE:
				//case MotionEvent.ACTION_MOVE:
					highlightTableRow((TableRow) v, false);
					break;
				default:
					highlightTableRow((TableRow) v, true);
			}
			return false;
		}
    };
    
    private TableRow.OnLongClickListener mRowOnLongClickListener = new TableRow.OnLongClickListener()
    {
    	@Override
		public boolean onLongClick(View v) {
    		mSelectedId = v.getId();
    		AlertDialog.Builder builder = new AlertDialog.Builder(FlightLogBrowseActivity.this);
			builder.setMessage("Delete this flight log entry?").setCancelable(false);
			builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Flight f = Flight.objects(FlightLogBrowseActivity.this).get(mSelectedId);
					if (f != null)
					{
						f.delete(FlightLogBrowseActivity.this);
						loadData();
						filterAndDisplayData();
					}
				}
			});
			builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
			return true;
    	}
    };
    
    private TableRow.OnFocusChangeListener mRowOnFocusChangeListener = new View.OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			highlightTableRow((TableRow) v, hasFocus);			
		}
    };
}
